<template>
    <div class="project-change-task-view">

      <modules-title class="title-position" titleName="项目计划变更">

        <template slot="btn">

          <el-button plain icon="el-icon-refresh-left" size="mini" @click="goBack">返回</el-button>
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="submitClick">提交申请</el-button>
<!--          <el-checkbox style="margin-left: 10px" v-model="isBaseLine">保存基线</el-checkbox>-->

        </template>

      </modules-title>

      <div class="pj-content" style="margin-top: 120px">

        <div class="top">

          <div class="left">

            <el-form :inline="true">
              <el-form-item label="只看里程碑">
                <el-checkbox v-model="planChecked" @change="planChange"></el-checkbox>
              </el-form-item>
              <el-form-item label="甘特图">
                <el-checkbox v-model="ganttChecked" @change="ganttChange"></el-checkbox>
              </el-form-item>
            </el-form>
          </div>

          <div class="right">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="addPlan">新增里程碑</el-button>
          </div>

        </div>


        <wlGantt
          v-if="ganttChecked"
          ref="wl-gantt-demo"
          :edit="false"
          :check-source="false"
          :autoGanttDateType="false"
          :useCheckColumn="false"
          :use-check-column="false"
          use-index-column
          :end-date="endDate"
          :start-date="startDate"
          date-type="monthAndDay"
          :data="planChecked?tableData2:tableData"
          :contextMenuOptions="contextMenuOptions"
          :expandRowKeys="expandRowKeys"
        >

          <template>

            <el-table-column
              align="center"
              fixed
              prop="duration"
              width="100"
              label="工期（天）"
            >
            </el-table-column>

            <el-table-column
              align="center"
              fixed
              prop="foreground_task_name"
              width="100"
              label="前置任务"
            >
            </el-table-column>

            <el-table-column
              align="center"
              fixed
              width="100"
              label="负责人"
            >
              <template slot-scope="scope">
                <div v-if="scope.row.person_in_charge && scope.row.person_in_charge.member_id">
                  {{scope.row.person_in_charge.member_name}}
                </div>
              </template>
            </el-table-column>


            <el-table-column
              align="center"
              fixed
              type="index"
              width="60"
              label="操作"
            >
              <template slot-scope="scope">
                <el-dropdown v-if="scope.row.status != 6">
                <span class="el-dropdown-link">
                  ...
                </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-if="scope.row.level != 5">
                      <a class="opt-btn" style="color: dodgerblue" @click="addChilen(scope.row)">添加任务</a>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <a class="opt-btn" style="color: dodgerblue" @click="editClick(scope.row,scope.$index)">编辑</a>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.is_add">
                      <a class="opt-btn" style="color: dodgerblue" @click="deleteClick(scope.row.id)">删除</a>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <a class="opt-btn" style="color: dodgerblue" @click="addFiles(scope.row)">添加文档</a>
                    </el-dropdown-item>
                    <!--                  <el-dropdown-item v-if="checkTop(scope.row.id) && scope.row.is_add">-->
                    <!--                    <a class="opt-btn" style="color: dodgerblue"  @click="topClick(scope.row.id)">上移</a>-->
                    <!--                  </el-dropdown-item>-->
                    <!--                  <el-dropdown-item v-if="checkBottom(scope.row.id) && scope.row.is_add">-->
                    <!--                    <a class="opt-btn" style="color: dodgerblue"  @click="bottomClick(scope.row.id)">下移</a>-->
                    <!--                  </el-dropdown-item>-->
                  </el-dropdown-menu>
                </el-dropdown>

                <el-popover
                  v-if="scope.row.is_out"
                  placement="top-start"
                  width="100"
                  trigger="hover">
                  <div style="color: red">
                    结束时间超出范围
                  </div>
                  <i slot="reference" class="el-icon-warning-outline" style="color: red;margin-left: 10px"></i>
                </el-popover>
              </template>
            </el-table-column>
          </template>

        </wlGantt>

        <el-table
          v-else
          size="medium"
          :data="planChecked?tableData2:tableData"
          border
          align="center"
          row-key="id"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          style="width: 100%">
          <el-table-column
            align="center"
            type="index"
            label="序号"
            width="50">
          </el-table-column>
          <el-table-column
            header-align="center"
            label="里程碑/任务名称">
            <template slot-scope="scope">

              <span v-if="(!scope.row.children || !scope.row.children.length) && scope.row.level == 1" style="padding-left: 25px">  </span>
              <span>{{scope.row.task_name}}</span>

            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="startDate"
            label="开始日期"
            width="150">
            <template slot-scope="scope">

              <span>{{scope.row.startDate}}</span>

            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="endDate"
            label="结束日期"
            width="150">
            <template slot-scope="scope">

              <span>{{scope.row.endDate}}</span>

            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="foreground_task_name"
            label="前置任务"
            width="150">
          </el-table-column>
          <el-table-column
            align="center"
            prop="duration"
            label="工期（天）"
            width="100">
          </el-table-column>
          <el-table-column
            align="center"
            prop="person"
            label="负责人"
            width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.person_in_charge && scope.row.person_in_charge.member_id">
                {{scope.row.person_in_charge.member_name}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="days"
            label="参与人"
            width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.task_member && scope.row.task_member.length > 0">
                <el-popover
                  placement="top-start"
                  width="100"
                  trigger="hover">
                  <div>
                    <div v-for="item in scope.row.task_member" style="padding-bottom: 5px">
                      <i class="el-icon-user">{{  item.member_name}}</i>
                    </div>
                  </div>
                  <i slot="reference" class="el-icon-user">{{scope.row.task_member.length}}</i>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="交付文档"
            width="100">
            <template slot-scope="scope">

              <div v-if="scope.row.files.length > 0">
                <el-popover
                  placement="top-start"
                  width="200"
                  trigger="hover">
                  <div>
                    <div v-for="item in scope.row.files" style="padding-bottom: 5px">
                      <i class="el-icon-document">{{  item.file_name}}</i>
                    </div>
                  </div>
                  <i slot="reference" class="el-icon-document">{{scope.row.files.length}}</i>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="阶段性评审"
            width="50">
            <template slot-scope="scope">
              <span>{{scope.row.periodical_review?'是':'否'}}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="强制验收"
            width="50">
            <template slot-scope="scope">
              <span>{{scope.row.mandatory_check?'是':'否'}}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
            width="60">

            <template slot-scope="scope">

              <el-dropdown v-if="scope.row.status != 6">
                <span class="el-dropdown-link">
                  ...
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="scope.row.level != 5">
                    <a class="opt-btn" style="color: dodgerblue" @click="addChilen(scope.row)">添加任务</a>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <a class="opt-btn" style="color: dodgerblue" @click="editClick(scope.row,scope.$index)">编辑</a>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.is_add">
                    <a class="opt-btn" style="color: dodgerblue" @click="deleteClick(scope.row.id)">删除</a>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <a class="opt-btn" style="color: dodgerblue" @click="addFiles(scope.row)">添加文档</a>
                  </el-dropdown-item>
<!--                  <el-dropdown-item v-if="checkTop(scope.row.id) && scope.row.is_add">-->
<!--                    <a class="opt-btn" style="color: dodgerblue"  @click="topClick(scope.row.id)">上移</a>-->
<!--                  </el-dropdown-item>-->
<!--                  <el-dropdown-item v-if="checkBottom(scope.row.id) && scope.row.is_add">-->
<!--                    <a class="opt-btn" style="color: dodgerblue"  @click="bottomClick(scope.row.id)">下移</a>-->
<!--                  </el-dropdown-item>-->
                </el-dropdown-menu>
              </el-dropdown>

              <el-popover
                v-if="scope.row.is_out"
                placement="top-start"
                width="100"
                trigger="hover">
                <div style="color: red">
                  结束日期超出范围
                </div>
                <i slot="reference" class="el-icon-warning-outline" style="color: red;margin-left: 10px"></i>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>

      </div>

      <el-dialog
        v-if="editShow"
        :title="title"
        :visible.sync="editShow"
        width="750px"
        :before-close="handleClose">

        <edit-task-view ref="editTask" :project="datas" :data="editItem" :documents="documents" :plans="plans" :members="members"></edit-task-view>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editShow = false">取 消</el-button>
          <el-button type="primary" @click="dialogConfirm">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="文档"
        :visible.sync="dialogVisible"
        width="500px"
        append-to-body
        :before-close="handleClose">

        <el-form ref="documentForm" :model="documentData" :rules="rules" class="demo-form-inline" label-width="130px" size="medium" label-position="left">
          <el-form-item label="文档名称" prop="file_name">
            <el-input v-model="documentData.file_name" placeholder="请输入文档名称" style="width: 100%" clearable></el-input>
          </el-form-item>
          <el-form-item label="文档类型" prop="file_type">
            <el-select v-model="documentData.file_type" placeholder="请选择文档类型" @change="typeChange" style="width: 100%" clearable>
              <el-option
                v-for="(item,index) in options"
                :key="index"
                :label="item.dict_val"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申报所需文件" prop="delivery">
            <el-switch v-model="documentData.need"></el-switch>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="filesConfirm">确 定</el-button>
        </span>
      </el-dialog>


      <el-dialog
        title="变更申请"
        v-if="changeVisible"
        :visible.sync="changeVisible"
        width="800px"
        :before-close="handleClose">

        <el-form ref="causeForm" :model="formData" class="demo-form-inline" label-width="150px" size="medium" label-position="left" :rules="rules">

          <el-form-item label="变更原因" prop="change_cause_id">
            <el-select v-model="formData.change_cause_id" @change="causeChange">
              <el-option
                v-for="item in causes"
                :key="item.id"
                :label="item.dict_val"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注" prop="work_content">
            <div class="textarea">
              <el-input
                v-model="formData.details_describe"
                type="textarea"
                :rows="2">
              </el-input>
            </div>

          </el-form-item>

          <el-form-item label="变更影响程度" prop="change_level_id">
            <el-select v-model="formData.change_level_id" @change="levelChange">
              <el-option
                v-for="item in changes"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="变更影响描述">
            <el-input v-model="formData.change_describe" ></el-input>
          </el-form-item>


        </el-form>

        <span slot="footer" class="dialog-footer">
        <el-button @click="changeVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeConfirm">提交审批</el-button>
      </span>
      </el-dialog>

    </div>
</template>

<script>
  import {lookInfoSet} from "../../../../api/printSetting";
  import editTaskView from "./modules/editTaskView";

    export default {
        name: "index",
        components:{editTaskView},
        data:function () {
            return{
                title:'编辑任务',
                beforeData:[],
                isBaseLine:false,
                datas:{},
                planChecked:false,
                ganttChecked:false,
                endDate:'',
                startDate:'',
                tableData:[],
                tableData2:[],
                contextMenuOptions: [
                    { label: "任务名称", prop: "name" },
                    { label: "计划开始时间", prop: "startDate" },
                    { label: "计划结束时间", prop: "endDate" },
                ],
                expandRowKeys: ["1"],

                id:1,
                isEdit:false,
                editItem:{},

                documents:{
                    id:1,
                    list:[]
                },
                plans:[],
                members:[],
                options: [],

                editShow:false,

                dialogVisible:false,
                documentData:{},

                changeVisible:false,

                formData:{},
                changes:[
                    {
                        value:1,
                        label:'轻微'
                    },
                    {
                        value:2,
                        label:'一般'
                    },
                    {
                        value:3,
                        label:'严重'
                    },
                ],
                causes:[],
                rules: {
                    startDate: [
                        { type: 'date', required: true, message: '请选择开始日期', trigger: 'change' }
                    ],
                    endDate: [
                        { type: 'date', required: true, message: '请选择结束日期', trigger: 'change' }
                    ],
                    duration: [
                        { required: true, message: '请输入工期', trigger: 'blur' }
                    ],
                    change_cause_id: [
                        { required: true, message: '请选择变更原因', trigger: 'change' }
                    ],
                    change_level_id:[
                        { required: true, message: '请选择变更影响程度', trigger: 'change' }
                    ],
                    file_name: [
                        { required: true, message: '请输入名称', trigger: 'blur' }
                    ],
                    file_type: [
                        { required: true, message: '请选择文档类型', trigger: 'change' }
                    ],
                },

            }
        },
        mounted:function() {
            if (this.$route.query.id){
                this.getData(this.$route.query.id);
            }
            this.options = this.$store.getters.sysDic('file_type')

            lookInfoSet({dictType:'project_change_reason'}).then(res=>{
                if (res.code == 200){
                    this.causes = res.data
                }
            })
        },
        methods:{
            submitClick:function(){
                if (!this.checkTaskData(this.tableData,this.datas.plan_start_time,this.datas.plan_end_time)){
                    return false;
                }
                this.changeVisible = true;

            },
            dealData:function(list){
                for (let i = 0; i < list.length; i++){
                    let data = list[i]
                    data.task_member_id = []
                    data.task_member.forEach(item=>{
                        data.task_member_id.push(item.member_id)
                    })

                    if (data.children && data.children.length > 0){
                        this.dealData(data.children)
                    }
                    if (data.level == 1){
                        data.task_type = "1"
                    }else{
                        data.task_type = (data.children && data.children.length) ? "2" : "3"
                    }
                    data.sort = i+1;
                }
            },
            changeConfirm:function(){

                this.dealData(this.tableData)
                if (this.$refs.causeForm){
                    this.$refs.causeForm.validate((valid)=>{
                        if (valid){
                            let data = {
                                object_id:this.datas.id,
                                project_id:this.datas.id,
                                project_name:this.datas.project_name,
                                change_type:4,
                                reason_id:this.formData.change_cause_id,
                                reason:this.formData.change_cause,
                                description:this.formData.details_describe,
                                level_id:this.formData.change_level_id,
                                level:this.formData.change_level,
                                change_describe:this.formData.change_describe,
                                tasks_after:this.tableData,
                                tasks_before:this.beforeData
                            }
                            this.changeVisible = false;
                            this.$api.PROJECT_START_CHANGE_CREATE(data).then(res=>{
                                if (res.code == 200){
                                    this.$message.success("提交成功")
                                    this.$router.back()
                                }else {
                                    this.$message.error(res.msg)
                                }
                            })
                        }
                    })
                }

            },
            causeChange:function(id){
                let index = this.causes.findIndex(a=>a.id == id)
                if (index != -1){
                    let data = this.causes[index]
                    this.formData.change_cause = data.dict_val;

                }
            },
            levelChange:function(id){
                let index = this.changes.findIndex(a=>a.value == id)
                if (index != -1){
                    let data = this.changes[index]
                    this.formData.change_level = data.label;
                }
            },
            checkTaskData:function(list,s_time,e_time){
                for (let i = 0; i < list.length; i++){
                    let data = list[i];
                    data._all_children = null;
                    data._cycle = null;
                    data._identityId = null
                    data._isLeaf = null;
                    data._level = null;
                    data._oldEndDate = null;
                    data._oldStartDate = null;
                    data._parent = null;
                    data._parents = null;

                    if (!data.status){
                        if (!data.task_name){
                            this.$message.error("请添加任务名称")
                            return false;
                        }
                        if (!data.start_date){
                            this.$message.error("请设置" + data.task_name + "的起始时间")
                            return false;
                        }
                        if (!data.end_date){
                            this.$message.error("请设置" + data.task_name + "的结束时间")
                            return false;
                        }
                        if (!data.duration){
                            this.$message.error("请设置" + data.task_name + "的工期")
                            return false;
                        }
                        if (!data.person_in_charge || !data.person_in_charge.member_id){
                            this.$message.error("请设置" + data.task_name + "的负责人")
                            return false;
                        }
                        if (!data.task_member_id || !data.task_member_id.length){
                            this.$message.error("请设置" + data.task_name + "的参与人")
                            return false;
                        }

                        if (new Date(data.start_date).getTime() < new Date(s_time).getTime()){
                            this.$message({
                                message: '请调整' + data.task_name + "的开始日期",
                                type: 'warning'
                            })
                            return false;
                        }

                        if (new Date(data.end_date).getTime() > new Date(e_time).getTime()){
                            this.$message({
                                message: '请调整' + data.task_name + "的结束日期",
                                type: 'warning'
                            })
                            return false;
                        }
                    }

                    if (data.children && data.children.length){
                        if (!this.checkTaskData(data.children,data.start_date,data.end_date)){
                            return false;
                        }
                    }
                }

                return true;
            },
            goBack:function(){
                this.$router.back();
            },
            getData:function(id){
                this.$api.PROJECT_MANAGER_PROJECT_DETAIL(id).then(res=>{
                    if (res.code == 200){
                        this.datas = {...res.data};
                        this.beforeData = JSON.parse(JSON.stringify(res.data.project_task))
                        if (this.datas){
                            this.startDate = this.dealDateStr(new Date(this.datas.plan_start_time))
                            this.endDate = this.dealDateStr(new Date(this.datas.plan_end_time))
                            this.tableData = this.datas.project_task


                            this.dealTaskData(this.tableData)
                            this.dealDocument();
                        }
                    }
                }).catch(err=>{

                })
            },
            dealDocument:function(){
                for (let i = 0; i < this.documents.list.length; i++){
                    let data = this.documents.list[i];
                    if (this.documents.id <= data.id){
                        this.documents.id = Number(data.id)+1;
                    }
                    data.id = data.id + ""
                }
            },
            dealTaskData:function(list){
                for (let i = 0; i < list.length; i++){
                    let data = list[i];
                    data.name = data.task_name;
                    data.startDate = this.dealDateStr(new Date(data.start_date))
                    data.endDate = this.dealDateStr(new Date(data.end_date))
                    data.person_id = data.person_in_charge.member_id
                    data.is_add = false;

                    this.plans.push(data);
                    this.documents.list = this.documents.list.concat(data.files)

                    if (data.children && data.children.length){
                        this.dealTaskData(data.children);
                    }
                }
            },
            planChange:function (value) {
                if (value){
                    this.tableData2 = [];
                    for (let i = 0; i < this.tableData.length; i++){
                        let data = {...this.tableData[i]};
                        data.children = [];
                        this.tableData2.push(data)
                    }
                }
            },
            ganttChange:function () {
                console.log(this.tableData)
            },
            handleClose:function(){
                this.editShow = false;
                this.dialogVisible = false;
                this.changeVisible = false;
            },
            bottomClick:function(id){
                let arr = this.findDataArr(id,this.tableData)

                if (arr.length > 1){
                    let data = [...this.tableData]
                    for (let i = 0; i < arr.length; i ++){
                        if (i == arr.length-2){
                            this.downGo(data[arr[i]].children,arr[i+1])
                            break;
                        }
                        data = data[arr[i]].children
                    }
                }else if (arr.length == 1){
                    this.downGo(this.tableData,arr[0])
                }
            },
            topClick:function(id){
                let arr = this.findDataArr(id,this.tableData)


                if (arr.length > 1){
                    let data = [...this.tableData]
                    for (let i = 0; i < arr.length; i ++){
                        if (i == arr.length-2){
                            this.upGo(data[arr[i]].children,arr[i+1])
                            break;
                        }
                        data = data[arr[i]].children
                    }
                }else if (arr.length == 1){
                    this.upGo(this.tableData,arr[0])
                }
            },
            downGo:function(arr,index){
                arr[index] = arr.splice(index+1, 1, arr[index])[0];
            },
            upGo:function(arr,index){
                arr[index] = arr.splice(index-1, 1, arr[index])[0];
            },
            // 检查上移
            checkTop:function(id){
                let arr = this.findDataArr(id,this.tableData)
                if (arr.length > 0 && arr[arr.length-1]){
                    return true
                }else{
                    return false
                }
            },
            // 检查下移
            checkBottom:function(id){
                let arr = this.findDataArr(id,this.tableData)

                let length = 0;
                if (arr.length > 1){
                    let data = [...this.tableData]
                    for (let i = 0; i < arr.length; i ++){
                        data = data[arr[i]].children
                        if (i == arr.length-2){
                            length = data.length;
                            break;
                        }
                    }
                }else if (arr.length == 1){
                    length = this.tableData.length;
                }

                if (arr.length > 0 && arr[arr.length-1] != length-1){
                    return true
                }else{
                    return false
                }
            },
            // 删除任务
            deleteClick:function(id){
                let arr = this.findDataArr(id,this.tableData)
                if (arr.length > 1){
                    let data = [...this.tableData]
                    for (let i = 0; i < arr.length; i ++){
                        if (i == arr.length-2){
                            data[arr[i]].children.splice(arr[arr.length-1],1)
                            break;
                        }
                        data = data[arr[i]].children
                    }
                }else if (arr.length == 1){
                    this.tableData.splice(arr[0],1)
                }

                let index = this.plans.findIndex(a=>a.id == id)
                if (index != -1){
                    let data = this.plans[index];
                    if (data.children && data.children.length){
                        let list = this.getChildren(data.children);
                        list.push(id)
                        for (let i = 0; i< list.length; i++){
                            let idx = this.plans.findIndex(a=>a.id == list[i])
                            if (idx != -1){
                                this.plans.splice(idx,1);
                            }
                        }
                    }else {
                        this.plans.splice(index,1);
                    }

                }
            },
            getChildren:function(list){
                let arr = [];
                for (let i = 0; i < list.length; i++){
                    arr.push(list[i].id);
                    if (list[i].children && list[i].children.length){
                        arr = arr.concat(this.getChildren(list[i].children))
                    }
                }
                return arr;
            },
            // 添加里程碑
            addPlan: function() {
                let data = this.createData()

                this.title= "新增里程碑"
                this.members = this.datas.member;
                this.addId = -1;
                this.isEdit = false;
                this.editItem = data;
                this.editShow = true;
                setTimeout( () => {
                    if (this.$refs.editTask){
                        this.$refs.editTask.dealPlanList();
                    }
                },500)
            },
            // 添加子任务
            addChilen:function (item){
                let num = item.level + 1

                let data = this.createData(item);

                this.title= "新增任务"
                this.members = item.task_member ? item.task_member : [];
                this.addId = item.id;
                this.isEdit = false;
                this.editItem = data;
                this.editShow = true;
                setTimeout(() => {
                    if (this.$refs.editTask){
                        let arr = this.findDataArr(this.addId,this.tableData);
                        let list = [];
                        let data = [...this.tableData];
                        for (let i = 0; i < arr.length; i++){
                            let a = data[arr[i]];
                            list.push(a.id);
                            if (arr.length > 1 && i != arr.length - 1){
                                data = a.children;
                            }
                        }
                        this.$refs.editTask.dealPlanList(list);
                    }
                },500)
            },
            // 编辑任务
            editClick: function(item,index) {
                let data = {...this.findData(item.id)}

                if (item.parent_id){
                    let parent = this.findData(item.parent_id)
                    this.members = parent.task_member ? parent.task_member : [];
                }else {
                    this.members = this.datas.member;
                }
                if (item.level == 1){
                    this.title= "编辑里程碑"
                }else{
                    this.title= "编辑任务"
                }

                this.editItem = data;
                this.editId = data.id;
                this.isEdit = true;
                this.editShow = true;
                setTimeout( () => {
                    if (this.$refs.editTask){
                        let arr = this.findDataArr(this.editId,this.tableData);
                        let list = [];
                        let data = [...this.tableData];
                        for (let i = 0; i < arr.length; i++){
                            let a = data[arr[i]];
                            list.push(a.id);
                            if (arr.length > 1 && i != arr.length - 1){
                                data = a.children;
                            }
                        }
                        this.$refs.editTask.dealPlanList(list);
                    }
                },500)
            },
            // 创建数据生成
            dialogConfirm: function(){
                if (this.$refs.editTask){
                    this.$refs.editTask.validateFun().then(()=>{
                        let data1 = {...this.editItem}
                        data1.name = data1.task_name

                        if (!this.isEdit){

                            if (this.addId == -1){
                                this.tableData.push(data1)
                            }else{
                                let ls = this.findDataArr(data1.parent_id,this.tableData)

                                let data = this.tableData
                                for (let i = 0; i < ls.length; i ++){

                                    if (!data[ls[i]].children){
                                        data[ls[i]].children = []
                                    }
                                    data = data[ls[i]].children

                                }
                                data.push(data1)

                            }
                            this.plans.push(data1);
                            console.log(this.tableData)
                        }else {
                            let arr = this.findDataArr(this.editId,this.tableData)

                            let data2 = {}
                            if (arr.length > 1){
                                let data = [...this.tableData]
                                for (let i = 0; i < arr.length; i ++){
                                    if (i == arr.length-1){
                                        data2 = {...data[arr[i]]};

                                        this.$set(data,arr[i],data1)
                                        break;
                                    }
                                    data = data[arr[i]].children
                                }
                            }else if (arr.length == 1){
                                data2 = {...this.tableData[arr[0]]}
                                this.$set(this.tableData,arr[0],data1)

                            }

                            for (let i = 0; i < data2.files.length; i++){
                                let doc = data2.files[i];
                                let index = this.documents.list.findIndex(a=>a.id == doc.id);
                                if (index != -1){
                                    this.documents.list.splice(index,1)
                                }
                            }
                            let index = this.plans.findIndex(a=>a.id == data1.id)
                            if (index != -1){

                                this.$set(this.plans,index,data1)
                            }
                        }

                        this.documentDeal(data1)

                        this.checkEndData(this.tableData);

                        this.editShow = false;
                    })
                }

            },
            // 处理文档
            documentDeal:function(data){

                for (let i = 0; i < data.files.length; i++){

                    let doc = data.files[i];
                    doc.task_id = data.id;
                    doc.task_name = data.task_name;

                    let index = this.documents.list.findIndex(a=>a.id == doc.id);

                    if (index == -1){
                        this.documents.list.push(doc)
                    }else{
                        this.$set(this.documents.list,index,doc);
                    }

                }

            },
            checkEndData:function(list){
                for (let i = 0; i < list.length; i++){
                    let data = list[i];
                    if (data.children && data.children.length > 0){
                        this.checkEndData(data.children);
                    }
                    this.checkOut(data);
                }
            },
            checkOut:function(data){
                data.is_out = false;
                if (data.endDate != "" && (data.children && data.children.length > 0)){
                    let date = new Date(data.endDate).getTime();

                    for (let i = 0; i < data.children.length; i++){
                        if (data.children[i].endDate != ""){
                            if (new Date(data.children[i].endDate).getTime() > date){
                                data.children[i].is_out = true;
                                data.is_out = true;
                            }
                        }
                    }
                }
            },
            addFiles:function (item) {

                this.documentData = {
                    id:"0",
                    file_name:'',
                    file_type:'',
                    type_name:'',
                    need:false,
                    task_id:item.id + "",
                    task_name:item.task_name,
                }
                this.dialogVisible = true;
            },
            filesConfirm:function () {

                if (this.$refs.documentForm){
                    this.$refs.documentForm.validate((valid) => {
                        if (valid){
                            let data = {...this.documentData}

                            data.id = this.documents.id + ""
                            this.documents.id++;
                            this.documents.list.push(data)
                            this.addDoc(data)

                            this.dialogVisible = false
                        }
                    })
                }

            },
            typeChange:function (id) {
                let index = this.options.findIndex(a=>a.id == id)
                if (index != -1){
                    let data = this.options[index];
                    this.documentData.file_type = data.id
                    this.documentData.type_name = data.dict_val
                }
                console.log(this.documentData)
            },
            // 查找任务数据
            findData:function(id){
                let arr = this.findDataArr(id,this.tableData);

                let data = {}
                if (arr.length == 1){
                    data = {...this.tableData[arr[0]]}
                }else {
                    let a = [...this.tableData]
                    for (let i = 0; i < arr.length; i++){
                        if (i == arr.length-1){
                            data = {...a[arr[i]]};
                        }else{
                            a = a[arr[i]].children;
                        }
                    }
                }
                return data;
            },
            // 查找任务路径
            findDataArr:function(id,list){
                let arr = [];
                for (let i = 0; i < list.length; i++){
                    if (list[i].id == id){
                        arr.push(i)
                        break
                    }else if (list[i].children && list[i].children.length > 0){
                        let a = this.findDataArr(id,list[i].children)
                        if (a.length > 0){
                            arr.push(i);
                            arr = arr.concat(a);
                            break;
                        }
                    }
                }

                return arr;
            },
            createData:function (item = null) {
                let data = {};
                data.id = this.id + "";
                data.task_name = ''
                data.level = item ? item.level + 1 : 1
                data.startDate = ""
                data.realStartDate = ""
                data.endDate = ""
                data.realEndDate = ""
                data.parent_id = item ? item.id : ""
                data.parent_name = item ? item.task_name : ''
                data.foreground_task_id = "";
                data.foreground_task_name = ''
                data.start_after_days = 0
                data.duration = 0
                data.periodical_review = false;
                data.mandatory_check = false;
                data.files = [];
                data.children = [];
                data.task_member = []
                data.task_member_id = []
                data.is_add = true;
                data.person_in_charge = {}
                data.person_id = "";
                data.person = "";
                data.isAdd = true;
                data.status = 0;

                this.id ++;
                return data;
            },
            dealDateStr:function(date){
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let day = date.getDate();
                if (month < 10){
                    month = "0" + month
                }
                if (day < 10){
                    day = "0" + day;
                }

                return year + "-" + month + "-" + day
            },
            deleteDoc:function (doc) {
                let arr = this.findDataArr(doc.task_id,this.tableData)

                let plan = {}
                if (arr.length > 1){
                    let data = [...this.tableData]
                    for (let i = 0; i < arr.length; i ++){
                        if (i == arr.length-1){
                            plan = data[arr[i]]
                            break;
                        }
                        data = data[arr[i]].children
                    }
                }else if (arr.length == 1){
                    plan = this.tableData[arr[0]]
                }

                let index = plan.files.findIndex(a=>a.id = doc.id)
                if (index != -1){
                    plan.files.splice(index,1);
                }

            },
            addDoc:function (doc) {
                let arr = this.findDataArr(doc.task_id,this.tableData)

                let plan = {}
                if (arr.length > 1){
                    let data = [...this.tableData]
                    for (let i = 0; i < arr.length; i ++){
                        if (i == arr.length-1){
                            plan = data[arr[i]]
                            break;
                        }
                        data = data[arr[i]].children
                    }
                }else if (arr.length == 1){
                    plan = this.tableData[arr[0]]
                }
                plan.files.push(doc)
            }
        }
    }
</script>

<style lang="scss">
  @import "../../../../assets/scss/views/projectManagement/list/change/changeTask.scss";
</style>
